package com.tuling.dao;

import com.tuling.Util.DruidUtils;
import com.tuling.domain.Cart;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao{
    private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
    @Override
    public int add(int uid, Cart cart) {
        String sql = "INSERT INTO shop (uid, fid, isStar, isCart) values (?, ?, ?, ?)";
        Object[] params = {cart.getUid(), cart.getFid(), cart.getIsStar(), cart.getIsCart()};
        try {
            int update = queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(int uid, Cart cart) {
        String sql  = "UPDATE shop SET uid =?, fid =?, isStar =?, isCart =? WHERE uid =? and fid = ?";
        Object[] params = {cart.getUid(), cart.getFid(), cart.getIsStar(), cart.getIsCart(), cart.getUid(), cart.getFid()};
        try {
            int update = queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int del(int uid, int fid) {
        String sql = "delete from shop where uid = ? and fid = ?";
        Object[] params = {uid, fid};
        try {
            int update = queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Cart find(int uid, int fid) {
        String sql = "select * from shop WHERE uid = ? and fid = ?";
        Object[] params = {uid, fid};
        try {
            Cart query = queryRunner.query(sql, new BeanHandler<>(Cart.class), params);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<Cart> findByUid(int uid) {
        String sql = "select * from shop WHERE uid = ?";
        Object[] params = {uid};
        try {
            List<Cart> query = queryRunner.query(sql, new BeanListHandler<>(Cart.class), params);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
